﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using RAP.Framework.Libary.DataSource.Model;
using RAP.Framework.Libary.Utils;

namespace RAP.Framework.Libary.DataSource.DataReader
{
  /// <summary>
  /// DataTable解析器
  /// </summary>
  public class DataTableParser : DataReaderParser
  {
    /// <summary>
    /// 将DataReader当前结果集转换成DataTable对象
    /// </summary>
    /// <param name="dataReader"></param>
    /// <param name="pickFields">读取第一条记录的指定列，默认读取所有数据的所有列</param>
    /// <param name="type">结果类型名称</param>
    /// <param name="parseContext">解析时用到的上下文对象</param>
    /// <returns></returns>
    public override ParseResult ParseData(IDataReader dataReader, IList pickFields, string type, DataParseContext parseContext)
    {
      var table = CreateDataModel() as DataTable;
      var fields = this.GetFields(dataReader, pickFields);
      var onlyGetFirstData = pickFields.IsNotNullOrEmpty();
      //获取表的列头
      for (var i = 0; i < fields.Count; i++)
      {
        var field = fields[i];
        table.Columns.Add(field.Name, field.Type.DBTypeToType());
      }

      //读取每一行数据
      while (dataReader.Read())
      {
        object[] data = new object[table.Columns.Count];
        dataReader.GetValues(data);
        table.Rows.Add(data);
        if (onlyGetFirstData)
        {
          //只获取第一行
          break;
        }
      }
      return new ParseResult
      {
        DataValue = table,
        DataCount = table.Rows.Count
      };
    }

    /// <summary>
    /// 创建数据模型对象
    /// </summary>
    /// <param name="resultTypeName">结果模型类型名称</param>
    /// <param name="properites">属性值集合</param>
    /// <returns></returns>
    public override object CreateDataModel(string resultTypeName = null, IDictionary properites = null)
    {
      var table = new DataTable();
      if (properites.IsNotNullOrEmpty())
      {
        object[] data = new object[properites.Keys.Count];
        var colIdx = 0;
        foreach (DictionaryEntry ety in properites)
        {
          var type = ety.Value?.GetType();
          table.Columns.Add(ety.Key.ToString());
          data[colIdx] = ety.Value;
          colIdx++;
        }
        table.Rows.Add(data);
      }
      return table;
    }
  }
}
